<?php
/**
 * Created by PhpStorm.
 * User: 图图
 * Date: 2021-6-8
 * Time: 16:27
 */


namespace app\console\controller;
use app\common\controller\Common;
use app\common\controller\Core;
use app\common\model\Orderqueue;
use app\common\service\AddService;
use app\user\model\Role as RoleModel;
use my\RedisPackage as redis;
use think\Exception;
use think\Request;
use think\Response;
use think\exception\HttpResponseException;
use think\Db;

/**
 * 前台公共控制器
 * @package app\index\controller
 */
class HandCard extends Common
{
    /**
     * 定时处理超时费用
     */
    public function overtime_fee(){
        //查找所有正在使用的手牌
        $data = Db::name('qt_hand_grant')
            ->field('grant.*,card.type')
            ->alias('grant')
            ->leftJoin('qt_hand_card card','card.id = grant.hand_card_id')
            ->where(['grant.status'=>'2','grant.hand_card_id'=>'5'])
            ->select();
        foreach ($data as $key=>$value){
            //查找是否有超时费
            $overtime = Db::name('qt_hand_card_price')->where(['store_id'=>$value['store_id'],'hand_card_type'=>$value['type']])->find();
            if(!empty($overtime)){
                $time = $value['create_time'] + ($overtime['buffer_time'] * 60) + ($overtime['free_time'] * 1800);
                if(time() > $time){
                    //计算超时费用
                    $difference = ceil((time() - $time) / 3600);
                    $step = ceil($difference / $overtime['overtime']);
                    $price = $step * $overtime['price'];
                    //给手牌插入金额
                    $goodsOrder = Db::name('qt_product_order')
                        ->where(['store_id'=>$value['store_id'],'hand_card_id'=>$value['hand_card_id'],'pay_status'=>'0'])
                        ->find();
                    if(empty($goodsOrder)){
                        //插入总订单
                        $orderInsert = [
                            'order_no' => c_order_sn('2'),
                            'store_id' => $value['store_id'],
                            'room_id' => $value['room_id'],
                            'engineer_id' => '',
                            'create_id' => '',
                            'hand_card_id' => $value['hand_card_id'],
                            'total_price' => $price,
                            'content' => !empty($data['content']) ? $data['content'] : '',
                            'order_status' => '0',
                            'create_time' => time(),
                        ];
                        $orderId = Db::name('qt_product_order')->insertGetId($orderInsert);
                    }else{
                        $orderId = $goodsOrder['id'];
                    }
                    $surplusStep = Db::name('qt_product_order_item')->where(['order_id'=>$orderId,'hand_card_id'=>$value['hand_card_id'],'business_type'=>'3','pay_status'=>'0'])->count();
                    dump($value['hand_card_id']);
                    dump($step);
                    dump($surplusStep);
                    $insert = [];
//                    try {
//                        Db::startTrans();
                        $money = 0;
                        //插入子订单
                        for ($i = 1; $i <= $step - $surplusStep;$i++){
                            $insert[$i] = [
                                'order_id'=>$orderId,
                                'room_id'=>$value['room_id'],
                                'hand_card_id'=>$value['hand_card_id'],
                                'store_id'=>$value['store_id'],
                                'goods_id'=>$overtime['product_id'],
                                'goods_name'=>$overtime['name'],
                                'goods_price'=>$overtime['price'],
                                'goods_total_price'=>$overtime['price'],
                                'goods_num'=>'1',
                                'create_time'=>time(),
                                'business_type'=>'3',
                            ];
                            $money+= $overtime['price'];
                        }
                        Db::name('qt_product_order_item')->insertAll($insert);
                        //更新手牌金额
                        Db::name('qt_hand_grant')->where(['id'=>$value['id']])->setInc('money',$money);
                        //处理提成记录
                        self::saveCommissionLog($orderId, $value['room_id']);
//                        Db::commit();
//                    } catch (Exception $exception) {
//                        Db::rollback();
//                    }
                }

            }
        }
    }



    /**
     * 定时处理过夜
     */
    public function overnight_fee(){
        //查找所有正在使用的手牌
        $data = Db::name('qt_hand_grant')
            ->field('grant.*,card.type')
            ->alias('grant')
            ->leftJoin('qt_hand_card card','card.id = grant.hand_card_id')
            ->where(['grant.status'=>'2','grant.is_overnight'=>'0'])
            ->select();
        foreach ($data as $key=>$value){
            //查找是否有超时费
            $overtime = Db::name('qt_hand_card_night_price')->where(['store_id'=>$value['store_id'],'hand_card_type'=>$value['type']])->find();
            if(!empty($overtime)){
                $time =  strtotime(date('Y-m-d'.'' .$overtime['start_time']));
                if(time() > $time){
                    //计算超时费用
                    $price = $overtime['price'];
                    //给手牌插入金额
                    $goodsOrder = Db::name('qt_product_order')
                        ->where(['store_id'=>$value['store_id'],'hand_card_id'=>$value['hand_card_id'],'pay_status'=>'0'])
                        ->find();
                    if(empty($goodsOrder)){
                        //插入总订单
                        $orderInsert = [
                            'order_no' => c_order_sn('2'),
                            'store_id' => $value['store_id'],
                            'room_id' => $value['room_id'],
                            'engineer_id' => '',
                            'create_id' => '',
                            'hand_card_id' => $value['hand_card_id'],
                            'total_price' => $price,
                            'content' =>'',
                            'order_status' => '0',
                            'create_time' => time(),
                        ];
                        $orderId = Db::name('qt_product_order')->insertGetId($orderInsert);
                    }else{
                        $orderId = $goodsOrder['id'];
                    }
                    try {
                        Db::startTrans();
                        $money = 0;
                        //插入子订单
                        $insert = [
                            'order_id'=>$orderId,
                            'room_id'=>$value['room_id'],
                            'hand_card_id'=>$value['hand_card_id'],
                            'store_id'=>$value['store_id'],
                            'goods_id'=>$overtime['product_id'],
                            'goods_name'=>$overtime['name'],
                            'goods_price'=>$overtime['price'],
                            'goods_total_price'=>$overtime['price'],
                            'goods_num'=>'1',
                            'create_time'=>time(),
                            'business_type'=>'4',
                        ];
                        Db::name('qt_product_order_item')->insertAll($insert);
                        //更新手牌金额
                        Db::name('qt_hand_grant')->where(['id'=>$value['id']])->setInc('money',$money);
                        //记录已经处理过过夜费
                        Db::name('qt_hand_grant')->where(['id'=>$value['id']])->update(['is_overnight'=>'1']);
                        //处理提成记录
                        self::saveCommissionLog($orderId, $value['room_id']);
                        Db::commit();
                    } catch (Exception $exception) {
                        Db::rollback();
                    }
                }

            }
        }
    }



    /**
     * 写提成记录表
     *
     * @param $order_id      [商品订单ID]
     * @param $room_id       [房间ID]
     */
    public static function saveCommissionLog($order_id, $room_id = '')
    {

        $goods_item = Db::name('qt_product_order_item')
            ->where('order_id', $order_id)->select();
        if (!empty($goods_item)) {
            $insert = [];
            foreach ($goods_item as $key => $value) {
                $checkFind = Db::name('qt_commission_log')->where(['order_project_id'=>$value['id'],'type'=>'2'])->find();
                if(empty($checkFind)){
                    $userGroup = Db::name('qt_users')->where(['id'=>$value['sale_id']])->value('group');
                    if($userGroup != null && $userGroup == '1'){
                        $userId = $value['sale_id'];
                    }else{
                        $userId = 0;
                    }
                    $insert[] = [
                        'store_id' => $value['store_id'],
                        'cashier_id' => !empty($value['sale_id']) ? $value['sale_id'] : 0,
                        'user_id' => $userId,
                        'room_id' => $room_id,
                        'money' => $value['goods_price'],
                        'commission' => $value['commission'],
                        'receiver' => $value['receiver'],
                        'product_id' => $value['goods_id'],
                        'type' => '2',
                        'created_time' => time(),
                        'is_pay' => '1',
                        'order_project_id' => $value['id'],
                    ];
                }
            }
            Db::name('qt_commission_log')->insertAll($insert);

        }
    }

}

